package com.example.vpnservicedemo;

import android.os.ParcelFileDescriptor;

import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.LinkedBlockingQueue;

public class WriteVpn {
    private ParcelFileDescriptor descriptor;

    private LinkedBlockingQueue<byte[]> queue = new LinkedBlockingQueue<>();


    public WriteVpn(ParcelFileDescriptor descriptor){
        this.descriptor = descriptor;

        ReadQueue readQueue = new ReadQueue();
        Thread thread = new Thread(readQueue);
        thread.setName("WriteVpnThread");
        thread.start();
    }

    public void push(byte[] data){
        queue.offer(data);
    }

    class ReadQueue implements Runnable {

        @Override
        public void run() {

            try (FileChannel writeChannel = new FileOutputStream(descriptor.getFileDescriptor()).getChannel()) {


                while (!Thread.interrupted()) {
                    try {

                        byte[] take = queue.take();


                        ByteBuffer wrap = ByteBuffer.wrap(take);

                        while (wrap.hasRemaining()){
                            writeChannel.write(wrap);
                        }


                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            } catch (Exception e) {
                System.out.println("WriteVpn 异常:" + e.getMessage());
                e.printStackTrace();
            }


        }
    }

}
